import socket
import struct

if __name__ == '__main__':
    tcp_client_socket = socket.socket()
    tcp_client_socket.connect(("127.0.0.1", 9002))
    name1 = ""
    while True:
        if name1 == "":
            name1 = input("请输入姓名")
            name1 = name1.encode("utf-8")
        message = input("请输出内容")
        message = message.encode("utf-8")
        values = (len(name1), len(message), name1, message)
        s = struct.Struct(f"BI20s80s")
        # 打包
        packed_data = s.pack(*values)
        # 发送
        tcp_client_socket.send(packed_data)

        recv_data = tcp_client_socket.recv(128)
        s1 = struct.unpack('I', recv_data[0:4])
        s2 = struct.unpack('I', recv_data[4:8])
        byProtocol, all_len, name, message = struct.unpack(f'BI20s80s', recv_data)
        name = name[0:s1[0]]
        message = message[0:s2[0]]
        print(
            f"采用协议{byProtocol},传输数据总长度{len(s1) + len(s2)},姓名:{name.decode('utf-8')},说:{message.decode('utf-8')}")
